﻿using Intex.Tools;
using System.Collections.Generic;
using INTEX.DataBase.Tools;
using ReflectionStudio.Core.Events;
using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Windows;
namespace WPFExcelReport
{
    public partial class YCAAUTOFSABData
    {

        public string ApplicationPath
        {
            get { return System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath); }
        }
        /// <summary>
        /// GetJob is used to collect the tasks to finish the order creation
        /// </summary>
        /// <param name="FInterID"></param>
        /// <returns></returns>
        public DataSet GetJob()
        {

            ArrayList tbs = new ArrayList() { "A", "B", "C" };
            string a = (string)tbs[0];
            DataSet Result = new DataSet();
            DataSet Return = new DataSet();

            try
            {
                string fileDone;
                string filestemp = @"C:\IntexReport\Data\YCAFSAB\01Temp";
                string[] files = System.IO.Directory.GetFiles(filestemp);
                foreach (string file in files)
                {
                    fileDone = file.Replace(@"\01Temp\", @"\02Incoming\");
                    System.IO.File.Move(file, fileDone);
                }
                string files2p = @"C:\IntexReport\Data\YCAFSAB\02Incoming";
                files = System.IO.Directory.GetFiles(files2p);

                if (files.Length > 0)
                {
                    string file = files[0];
                    Result.ReadXml(file);
                    Return.Merge(Result);
                    fileDone = file.Replace(@"\02Incoming\", @"\03Done\");
                    System.IO.File.Move(file, fileDone);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {

            }
            return Return;
        }
        private DataSet CheckABPART(ref bool IsSuccess, DataSet src, string file)
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            var query = from dwVA10 in src.Tables["ABPOS_MAT"].AsEnumerable()
                        select new
                        {
                            ABPART = dwVA10.Field<string>("ABPART"),
                            ABPVAR = dwVA10.Field<string>("ABPVAR"),
                            ABPFARBE = dwVA10.Field<string>("ABPFARBE"),
                        };
            foreach (var dwVA10 in query)
            {
                string var, art, color;
                art = Left(dwVA10.ABPART + "            ", 20);
                var = Left(dwVA10.ABPVAR + "                      ", 3);
                color = Left(dwVA10.ABPFARBE + "               ", 10);
                DataRow dwData = INTEXDB.FSFARBEN.NewRow();
                dwData["FSFMANDANT"] = "00";
                dwData["FSFART"] = art;
                dwData["FSFVAR"] = var;
                dwData["FSFFARBE"] = color;

                setResult = INTEXDBC.QueryFSFARBEN(dwData, 1);
                if (setResult.Tables.Count == 0)
                    continue;
                if (setResult.Tables[0].Rows.Count == 0)
                    continue;
                DataRow rowVA10 = setResult.Tables[0].Rows[0];
                var query1 = from row in src.Tables["ABPOS_MAT"].AsEnumerable()
                             where row["ABPART"] == dwVA10.ABPART
                             & row["ABPVAR"] == dwVA10.ABPVAR
                             & row["ABPFARBE"] == dwVA10.ABPFARBE
                             select row;
                if (query1.Count() > 0)
                {
                    foreach (DataRow row in query1)
                    {
                        row["COMMENTS"] = "款式档案存在";
                    }
                }
                else
                {
                    throw new Exception("款式:" + art + color + "color 未定义");
                }

            }
            setReturn.Merge(src);
            return setReturn;
        }
        private DataSet CheckFS05(ref bool IsSuccess, DataSet src, string file)
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();

            var query = from dwABPOS in src.Tables["ABPOS_MAT"].AsEnumerable()
                        select new
                       {
                           ABPART = dwABPOS.Field<string>("ABPART"),
                           ABPFARBE= dwABPOS.Field<string>("ABPFARBE"),
                       };

            string processedyarn = "";
            foreach (var dwABPOS in query)
            {
                string var, art, color;
                art = Left(dwABPOS.ABPART + "            ", 20);
                color = dwABPOS.ABPFARBE;
                if (processedyarn.Contains(art + ";"))
                    continue;
                processedyarn += art + ";";
                DataRow rowTemp = INTEXDB.FSSTUELI.NewRow();
                rowTemp["FSSMANDANT"] = "00";
                rowTemp["FSSART"] = art;
                setResult = INTEXDBC.QueryFSSTUELI(rowTemp, 2);
                var query1 = from rowx in src.Tables["ABPOS_MAT"].AsEnumerable()
                             where rowx["ABPART"].ToString().Trim() == art.Trim()
                             select rowx;
                foreach (DataRow row in query1)
                {
                    row["FS05"] = "N";
                    var qMain = from rowg in setResult.Tables["FSSTUELI"].AsEnumerable()
                                where rowg["FSSART"].ToString().Trim() == row["ABPART"].ToString().Trim()
                                 && rowg["FSSFARBE"].ToString().Trim() == row["ABPFARBE"].ToString().Trim()
                                     && rowg["FSSZUSCHN"].ToString().Trim() == "J"
                                select row;
                    if (qMain.Count() == 0)
                    {
                        row["FS05"] = "N";
                        IsSuccess = false;
                        throw new Exception("款式:" + art + color + "主面料 未定义");
                    }
                    var query2 = from rowg in setResult.Tables["FSSTUELI"].AsEnumerable()
                                 where rowg["FSSART"].ToString().Trim() == row["ABPART"].ToString().Trim()
                                 select row;
                    if (query2.Count() > 0)
                    {
                        row["FS05"] = "Y";
                        var query3 = from rowb in src.Tables["ABPOS_EXT"].AsEnumerable()
                                     where rowb["ABPART"].ToString().Trim() == row["ABPART"].ToString().Trim()
                                     select rowb;
                        foreach (DataRow rowb in query3)
                        {
                            rowb["FS05"] = "Y";
                        }
                    }
                    else
                    {
                        IsSuccess = false;
                        throw new Exception("款式:" + art + color + "BOM 未定义");
                    }
                }
            }
            setReturn.Merge(src);
            return setReturn;
        }
        private DataSet ConvertToLine(DataSet src, string file)
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            DataRow rwABP = null;
            double qty = 0;
            Convert2Intex = new Convert2Intex(SetExt, dwIntexStd, OracleDB, proxy);
            dwIntexStd = Convert2Intex.dwIntexStd;
            if (src.Tables.Contains("ABPOS_EXT"))
            {
                src.Tables["ABPOS_EXT"].Clear();
            }
            Dictionary<string, int> abpline = new Dictionary<string, int>();
            string art = "";
            string processed = "";
            int pos = 1;
            var query = from dwMTX in src.Tables["ABPOS_MAT"].AsEnumerable()
                        select dwMTX;
            foreach (DataRow dwMTX in query)
            {
                string sqty = dwMTX["ABPGROES"].ToString();
                art = dwMTX["ABPAUFKRS"].ToString().Trim() + dwMTX["ABPAUFLFD"].ToString().Trim();
                if (!processed.Contains(art + ";"))
                {
                    processed += art + ";";
                    abpline.Add(art, 0);
                }
                if (sqty.Trim() != "")
                {
                    qty = System.Convert.ToDouble(sqty);
                    if (qty > 0)
                    {

                        dwMTX["ABPGROE"] = "S";
                        dwMTX["ABPSOLLMENGE7"] = dwMTX["ABPGROES"];
                        setResult = Convert2ABPOS_EXT(dwMTX);
                        pos = abpline[art];
                        pos++;
                        abpline[art] = pos;
                        setResult.Tables[0].Rows[0]["ABPAUFPOS"] = pos;
                        setReturn.Merge(setResult);
                    }
                }
                sqty = dwMTX["ABPGROEM"].ToString();
                if (sqty.Trim() != "")
                {
                    qty = System.Convert.ToDouble(sqty);
                    if (qty > 0)
                    {
                        dwMTX["ABPGROE"] = "M";
                        dwMTX["ABPSOLLMENGE7"] = dwMTX["ABPGROEM"];
                        setResult = Convert2ABPOS_EXT(dwMTX);
                        pos = abpline[art];
                        pos++;
                        abpline[art] = pos;
                        setResult.Tables[0].Rows[0]["ABPAUFPOS"] = pos;
                        setReturn.Merge(setResult);
                    }
                }
                sqty = dwMTX["ABPGROEL"].ToString();
                if (sqty.Trim() != "")
                {
                    qty = System.Convert.ToDouble(sqty);
                    if (qty > 0)
                    {
                        dwMTX["ABPGROE"] = "L";
                        dwMTX["ABPSOLLMENGE7"] = dwMTX["ABPGROEL"];
                        setResult = Convert2ABPOS_EXT(dwMTX);
                        pos = abpline[art];
                        pos++;
                        abpline[art] = pos;
                        setResult.Tables[0].Rows[0]["ABPAUFPOS"] = pos;
                        setReturn.Merge(setResult);
                    }
                }
                sqty = dwMTX["ABPGROEXL"].ToString();
                if (sqty.Trim() != "")
                {
                    qty = System.Convert.ToDouble(sqty);
                    if (qty > 0)
                    {
                        dwMTX["ABPGROE"] = "XL";
                        dwMTX["ABPSOLLMENGE7"] = dwMTX["ABPGROEXL"];
                        setResult = Convert2ABPOS_EXT(dwMTX);
                        pos = abpline[art];
                        pos++;
                        abpline[art] = pos;
                        setResult.Tables[0].Rows[0]["ABPAUFPOS"] = pos;
                        setReturn.Merge(setResult);
                    }
                }
            }
            return setReturn;
        }
        private DataSet ConsolidateData(ref bool IsSuccess, DataSet src, string file)
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            bool IsCheckABPART = false;
            bool IsCheckGS08 = true;
           
                //获取ABPOS_EXT的VA10
                //查找对应的GS07
                //更新ABPOS_EXT
                //更新EXCEL
                if (!src.Tables.Contains("ABPOS_MAT"))
                {
                    setReturn.Merge(src);
                    IsSuccess = false;
                    return setReturn;
                }
                if (src.Tables["ABPOS_MAT"].Rows.Count == 0)
                {
                    setReturn.Merge(src);
                    IsSuccess = false;
                    return setReturn;
                }
                if (IsCheckABPART)
                {
                    setResult = CheckABPART(ref IsSuccess, src, file);
                    setReturn.Merge(setResult);
                }
                if (IsCheckGS08)
                {
                    setResult = CheckFS05(ref IsSuccess, src, file);
                    setReturn.Merge(setResult);
                }
         
            return setReturn;
        }
        private void SaveExcel(DataSet src, string ShortName, string file, string fileroot)
        {
            string xml = @"C:\IntexReport\Data\YCAFSAB\01Temp\" + ShortName.Replace(".xls", "_" + DateTime.Now.ToFileTime().ToString() + ".XML");
            if (System.IO.File.Exists(xml))
            {
                System.IO.File.Delete(xml);
            }
            if (src != null)
            {
                src.WriteXml(xml);
            }
            exAgent.SetCurrentSheet("ABPOS_MAT");
            int x = 3;
            int y = 1;
            exAgent.DataTableToExcel(src.Tables["ABPOS_MAT"], 3, 1);
            exAgent.SetCurrentSheet("ABPOS_EXT");
            x = 3;
            y = 1;
            exAgent.DataTableToExcel(src.Tables["ABPOS_EXT"], 3, 1);
            exAgent.Save();
            exAgent.Close();
            exAgent.SetCurrentSheet("ABPOS_MAT");
            if (System.IO.File.Exists(fileroot + "\\P_" + ShortName))
            {
                System.IO.File.Delete(fileroot + "\\P_" + ShortName);
            }
            System.IO.File.Copy(file, fileroot + "\\P_" + ShortName);
            System.IO.File.Delete(file);
            EventDispatcher.Instance.RaiseStatus("装载:" + ShortName + "完成", StatusEventType.StopProgress);
        }
        private void CheckDirectory()
        {
            if (!System.IO.Directory.Exists("C:\\IntexReport"))
            {
                System.IO.Directory.CreateDirectory("C:\\IntexReport");
            }

            if (!System.IO.Directory.Exists("C:\\IntexReport\\Data"))
            {
                System.IO.Directory.CreateDirectory("C:\\IntexReport\\Data");
            }
            if (!System.IO.Directory.Exists("C:\\IntexReport\\Data\\YCAFSAB"))
            {
                System.IO.Directory.CreateDirectory("C:\\ntexReport\\Data\\YCAFSAB");
            }
            if (!System.IO.Directory.Exists("C:\\IntexReport\\Data\\YCAFSAB\\EXCEL"))
            {
                System.IO.Directory.CreateDirectory("C:\\IntexReport\\Data\\YCAFSAB\\EXCEL");
            }
            if (!System.IO.Directory.Exists("C:\\IntexReport\\Data\\YCAFSAB\\01Temp"))
            {
                System.IO.Directory.CreateDirectory("C:\\IntexReport\\Data\\YCAFSAB\\01Temp");
            }
            if (!System.IO.Directory.Exists("C:\\IntexReport\\Data\\YCAFSAB\\02Incoming"))
            {
                System.IO.Directory.CreateDirectory("C:\\IntexReport\\Data\\YCAFSAB\\02Incoming");
            }
            if (!System.IO.Directory.Exists("C:\\IntexReport\\Data\\YCAFSAB\\03Done"))
            {
                System.IO.Directory.CreateDirectory("C:\\IntexReport\\Data\\YCAFSAB\\03Done");
            }

        }
        public DataSet LoadExcelData()
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            bool IsSuccess = true;
            try
            {

                CheckDirectory();
                string fileroot = @"C:\IntexReport\Data\YCAFSAB\EXCEL";
                string[] files = System.IO.Directory.GetFiles(fileroot);
                foreach (string file in files)
                {
                    string ShortName = file.Substring(file.LastIndexOf("\\") + 1);
                    if (!ShortName.StartsWith("FSAB"))
                        continue;
                    EventDispatcher.Instance.RaiseStatus("装载:" + ShortName + "开始", StatusEventType.StopProgress);
                    if (exAgent == null)
                    {
                        exAgent = new ExcelX.ExcelLib.ExcelAgent(file);
                    }
                    if (System.IO.File.Exists(file))
                    {
                        setResult = new DataSet();
                        setResult = exAgent.LoadDataTableDef(file, "", 50);
                        if (setResult.Tables.Contains("ABPOS_EXT"))
                        {
                            setResult.Tables["ABPOS_EXT"].Clear();
                        }
                        setReturn.Merge(setResult);
                        setResult = ConvertToLine(setResult, file);
                        setReturn.Merge(setResult);
                        setResult = ConsolidateData(ref IsSuccess, setReturn, file);

                        if (!IsSuccess)
                        { 
                            break;
                        }
                        setReturn = new DataSet();
                        setReturn.Merge(setResult);
                        SaveExcel(setReturn, ShortName, file, fileroot);
                    }
                }

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
                MessageBox.Show(ex.Message, ex.StackTrace);
            }
            finally
            {
                if (exAgent != null)
                {
                    exAgent.Save();
                    exAgent.Close();
                    exAgent.Dispose();
                    exAgent.KillExcelProcess();
                    GC.Collect();
                    exAgent = null;
                }
            }
            return setReturn;
        }

    }
}
